package com.app.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.model.WechatMessageTemplate;
import com.app.mapper.WechatMessageTemplateMapper;
import com.app.service.IWechatMessageTemplateService;
import com.app.utils.HttpClientUtil;
import com.app.utils.WXConstant;
import com.app.utils.WechatUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.app.utils.WechatUtil.postToken;

/**
 * <p>
 * 微信订阅消息模板 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2024-08-09
 */
@Service
public class WechatMessageTemplateServiceImpl extends ServiceImpl<WechatMessageTemplateMapper, WechatMessageTemplate> implements IWechatMessageTemplateService {





    public JSONObject pushmessage(String openId) throws Exception{

        String accessToken  = postToken(WXConstant.Official_Account_Appid, WXConstant.Official_Account_Secret);

        System.err.println("accessToken----"+accessToken);
        String message_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        message_url = message_url.replace("ACCESS_TOKEN", accessToken);

        JSONObject data = new JSONObject();
        data.put("touser", openId);
        data.put("template_id", "UWarcMoouE5pCznzo1Bsi7w2up7yGwo09drxdlgsJqM");
        data.put("page", "index");

        JSONObject params = new JSONObject();

        JSONObject time2 = new JSONObject();
        time2.put("value", "2024-06-23 12:50:37");

        JSONObject thing3 = new JSONObject();
        thing3.put("value", "卢小林");

        JSONObject thing4 = new JSONObject();
        thing4.put("value", "皮肤保养");

        JSONObject thing5 = new JSONObject();
        thing5.put("value", "测试店铺");

        params.put("time2", time2);
        params.put("thing3", thing3);
        params.put("thing4", thing4);
        params.put("thing5", thing5);


        params.put("thing1", "您的订单已支付成功");
        data.put("data", params);
        String resultStr = HttpUtil.post(message_url, data.toJSONString());
        return JSONObject.parseObject(resultStr);
    }


    public JSONObject pushmessageTest(String openId, String template_type, List<String> paramsData) {


        JSONObject result = new JSONObject();
        QueryWrapper<WechatMessageTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_type", template_type);
        WechatMessageTemplate wechatMessageTemplate = this.getOne(queryWrapper);
        if (wechatMessageTemplate == null) {
            result.put("code", 1);
            result.put("msg", "消息模板不存在");
            return result;
        }
        String message_key = wechatMessageTemplate.getMessageKey();
        List<String> messageKeys = Arrays.asList(message_key.split(","));
        if (messageKeys.size() != paramsData.size()){
            result.put("code", 1);
            result.put("msg", "参数数量与模板key值不对应");
            return result;
        }
        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(openId)
                // 模板id
                .templateId(wechatMessageTemplate.getTemplateId())
                // 模板跳转链接
                .build();

        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first","您好,您有一条新的通知", "#FF00FF"));
        for (int i = 0; i < messageKeys.size(); i++){
            templateMessage.addData(new WxMpTemplateData(messageKeys.get(i),paramsData.get(i), "#FF00FF"));
        }
        String msgId = null;
        try {
            // 发送模板消息
            msgId = WXConstant.officialAccountwxMpService().getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        result.put("code", 0);
        result.put("msg", msgId);
        return result;
    }



    public JSONObject sendWeChatMessageSubscriptionNotifications(String openId, String template_type, List<String> paramsData) throws Exception {
        JSONObject result = new JSONObject();
        QueryWrapper<WechatMessageTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_type", template_type);
        WechatMessageTemplate wechatMessageTemplate = this.getOne(queryWrapper);
        if (wechatMessageTemplate == null) {
            result.put("code", 1);
            result.put("msg", "消息模板不存在");
            return result;
        }
        String message_key = wechatMessageTemplate.getMessageKey();
        List<String> messageKeys = Arrays.asList(message_key.split(","));
        if (messageKeys.size() != paramsData.size()){
            result.put("code", 1);
            result.put("msg", "参数数量与模板key值不对应");
            return result;
        }

        String accessToken = WechatUtil.redisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        JSONObject data = new JSONObject();
        data.put("touser", openId);
        data.put("template_id", wechatMessageTemplate.getTemplateId());
        data.put("page", "index");

        JSONObject params = new JSONObject();
        for (int i = 0; i < messageKeys.size(); i++){
            JSONObject thing = new JSONObject();
            thing.put("value", paramsData.get(i));
            params.put(messageKeys.get(i), thing);
        }
        data.put("data", params);
        String resultStr = HttpUtil.post(url, data.toJSONString());
        result = JSONObject.parseObject(resultStr);
        return result;
    }

}
